package com.zj.juc.study.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName MyRotationLock
 * @Description 自旋锁
 * @createTime 2025年01月02日 22:25
 */
public class MyRotationLock {
    //通过CAS操作完成自旋锁，A线程先进来调用myLock方法自己持有锁5秒，B随后进来后发现锁被持有，自旋等待，直到A线程释放锁

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock(){
        Thread currentThread = Thread.currentThread();
        //第一遍进来肯定是null，所以操作成功，现在是A拿锁，B线程进来的时候发现锁被A拿着的，所以B自旋
        while (!atomicReference.compareAndSet(null,currentThread)){
            //未修改成功就循环

        }
        System.out.println(Thread.currentThread().getName()+"come in ");

    }

    public void unLock(){
        Thread currentThread = Thread.currentThread();
        //A现在拿着锁，它想要释放锁，持有锁的是A,所以操作成功，atomic里面是null，b再进来发现是null，所以b也释放了锁
        atomicReference.compareAndSet(currentThread, null);
        System.out.println(Thread.currentThread().getName()+"unlock");
    }

    public static void main(String[] args) {
        MyRotationLock myRotationLock = new MyRotationLock();
        Thread a =  new Thread(()->{
            myRotationLock.lock();//A拿锁
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myRotationLock.unLock();//5秒后A释放锁
        },"A");
        a.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread b = new Thread(()->{
            myRotationLock.lock();//B拿锁，但是B自旋
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myRotationLock.unLock();
        },"B");
        b.start();
    }

}

class MyLock{

}
